<template>
  <el-image
    ref="mainRef"
    :src="srcImage"
    v-bind="attrs"
    :style="{
      width: props.width,
      height: props.height,
    }"
  >
    <template v-for="(_, slotName) in slots" #[slotName]="slotData">
      <slot :name="slotName" v-bind="slotData || {}"></slot>
    </template>
  </el-image>
</template>

<script lang="ts" setup>
const props = defineProps({
  src: {
    type: [Promise, String],
    required: true,
  },
  width: {
    type: String,
    default: "auto",
  },
  height: {
    type: String,
    default: "auto",
  },
});
const srcImage = ref("");
watch(
  () => props.src,
  () => {
    const type = Object.prototype.toString.call(props.src);
    if (type === "[object Promise]") {
      (props.src as Promise<{ default?: string }>)
        .then((res) => {
          srcImage.value = res.default || "";
        })
        .catch(() => {
          if (!slots.error) {
            srcImage.value = config.image.default.imageError;
          }
        });
    } else if (type === "[object String]") {
      srcImage.value = props.src as string;
    }
  },
  {
    immediate: true,
  }
);

const mainRef = ref(null);
const attrs = useAttrs();
const slots = useSlots();
defineExpose({
  mainRef,
});
</script>

<style lang="scss">
.component-UseImage {
  width: 100%;
}
</style>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "UseImage",
});
</script>
